﻿using System;
using System.Collections;
using System.Collections.Generic;
using Core.Base;
using Core.Base.Module;
using Core.Mgr;
using Global.Mgr;
using Global.Module;
using Logic.Hall.Module;
using UnityEngine.SceneManagement;

namespace Core.Mgrs
{
    /// <summary>
    /// 场景管理器
    /// </summary>
    public class SceneMgr : BaseMgr
    {
        ///当前场景模块,在场景切换的时候卸载上一个场景的Module
        private BaseModule curModule;


        public override void OnInit()
        {
            base.OnInit();
            curModule = ModuleMgr.Ins.RegModule<HallModule>();
        }

        /// <summary>
        /// 异步加载指定场景（除大厅）
        /// </summary>
        /// <param name="sceneName">目标场景名</param>
        /// <param name="cb">加载完成的回调</param>
        public void LoadSceneAsync<T>(string sceneName, Action cb = null) where T : BaseModule
        {
            if (sceneName == "Empty" || sceneName == "Hall")
            {
                return;
            }

            KKGL.MainBehaviour.StartCoroutine(_LoadScene(sceneName, delegate
            {
                if (curModule != null)
                {
                    ModuleMgr.Ins.UnRegModule(curModule);
                }

                curModule = ModuleMgr.Ins.RegModule<T>();
                cb?.Invoke();
            }));
        }

        /// <summary>
        /// 加载大厅
        /// </summary>
        public void LoadHall(Action cb = null)
        {
            KKGL.MainBehaviour.StartCoroutine(_LoadScene("Empty", delegate
            {
                if (curModule != null)
                {
                    ModuleMgr.Ins.UnRegModule(curModule);
                }

                curModule = ModuleMgr.Ins.RegModule<HallModule>();
                cb?.Invoke();
            }));
        }

        private IEnumerator _LoadScene(string sceneName, Action cb = null)
        {
            if (SceneManager.GetActiveScene().name != sceneName)
            {
                yield return SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single);
                GC.Collect();
                cb?.Invoke();
            }
        }
    }
}